package xyz.jcat.sco.gateway.oauth2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;

@EnableWebFluxSecurity
public class SecurityConfig {

    @Autowired
    private ServerAuthenticationEntryPoint serverAuthenticationEntryPoint;
    @Autowired
    private ServerAccessDeniedHandler serverAccessDeniedHandler;
    @Autowired
    private ReactiveAuthorizationManager reactiveAuthorizationManager;

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {

        http.cors().and().csrf().disable();

        http.authorizeExchange()
                //TODO
                .pathMatchers("/sco/admin/oauth2/oauth/token").permitAll()
                .anyExchange()
                .access(reactiveAuthorizationManager)
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(serverAuthenticationEntryPoint)
                .accessDeniedHandler(serverAccessDeniedHandler);

        http.oauth2ResourceServer()
                .opaqueToken()
                .and()
                .authenticationEntryPoint(serverAuthenticationEntryPoint)//认证异常处理
                .accessDeniedHandler(serverAccessDeniedHandler)//权限异常处理
        ;

        return http.build();
    }

}
